<template>
  <div class="page-list">
    <t-card title="页面组件管理" bordered>
      <!-- 表格 -->
      <t-table
        :data="pageList"
        :columns="columns"
        :loading="loading"
        row-key="id"
        bordered
        hover
      />

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <t-pagination
          :total="total"
          :page-size="pageSize"
          :current="pageNum"
          @change="onPageChange"
          @page-size-change="onPageSizeChange"
        />
      </div>
    </t-card>

    <!-- 编辑弹框 -->
    <t-dialog
      v-model:visible="showEditDialog"
      header="组件信息"
      confirm-btn="保存"
      cancel-btn="取消"
      @confirm="handleSaveEdit"
      width="600"
    >
      <t-form :data="editForm" label-width="100" label-align="right">
        <t-form-item label="页面ID">
          <t-input v-model="editForm.pageId" placeholder="请输入页面ID" />
        </t-form-item>
        <t-form-item label="组件ID">
          <t-input v-model="editForm.componentId" placeholder="请输入组件ID" />
        </t-form-item>
        <t-form-item label="组件类型">
          <t-input v-model="editForm.componentType" placeholder="请输入组件类型" disabled />
        </t-form-item>

        <!-- 通用组件类型 -->
        <template
          v-if="
            editForm.componentType !== 'swiper' &&
            editForm.componentType !== 'news' &&
            editForm.componentType !== 'menus' &&
            editForm.componentType !== 'commodity'
          "
        >
          <t-form-item label="组件数据(JSON)">
            <t-textarea
              v-model="editForm.dataJson"
              placeholder="请输入组件数据JSON"
              rows="6"
            />
          </t-form-item>
        </template>

        <!-- Swiper 编辑 -->
        <template v-else-if="editForm.componentType === 'swiper'">
          <t-form-item label="轮播图片">
            <t-upload
              v-model="fileList"
              theme="image"
              tips="可上传多张图片"
              :action="uploadUrl"
              multiple
              :max="10"
              accept="image/*"
              :auto-upload="true"
              @success="handleUploadSuccess"
              @remove="handleUploadRemove"
            />
          </t-form-item>
        </template>

        <!-- Menus 编辑 -->
        <template v-else-if="editForm.componentType === 'menus'">
          <div style="margin-bottom: 10px;">
            <t-button size="small" theme="primary" @click="addMenuItem">+ 添加顶级菜单</t-button>
          </div>

          <t-collapse>
            <t-collapse-panel
              v-for="(item, index) in menusData"
              :key="index"
              :header="`菜单 ${index + 1}: ${item.label || '新菜单'}`"
            >
              <template #actions>
                <t-button size="small" theme="danger" variant="text" @click.stop="removeMenuItem(index)">删除</t-button>
              </template>

              <t-form :data="item" label-width="80" label-align="right" style="padding-top: 10px;">
                <t-form-item label="标签(label)">
                  <t-input v-model="item.label" placeholder="例如：家用电器" />
                </t-form-item>
                <t-form-item label="值(value)">
                  <t-input v-model="item.value" placeholder="例如：appliances" />
                </t-form-item>
                <t-form-item label="图标(icon)">
                  <t-input v-model="item.icon" placeholder="例如：app" />
                </t-form-item>

                <t-divider>Tabs</t-divider>
                <t-form-item label="Tabs">
                  <div style="width: 100%;">
                    <div v-for="(tab, tabIndex) in item.menu.tabs" :key="tabIndex" class="menu-editor-box">
                      <t-form-item label="标签" label-width="50px">
                        <t-input v-model="tab.label" placeholder="Tab 标签" />
                      </t-form-item>
                      <t-form-item label="值" label-width="50px">
                        <t-input v-model="tab.value" placeholder="Tab 值" />
                      </t-form-item>
                      <t-button size="small" theme="danger" variant="outline" @click="removeTab(item.menu, tabIndex)">删除 Tab</t-button>
                    </div>
                    <t-button size="small" theme="primary" variant="dashed" @click="addTab(item.menu)" block>+ 添加 Tab</t-button>
                  </div>
                </t-form-item>
              </t-form>
            </t-collapse-panel>
          </t-collapse>
        </template>

        <!-- News 编辑：改为弹窗选择新闻 -->
        <template v-else-if="editForm.componentType === 'news'">
          <t-form-item label="新闻选择">
            <t-button theme="primary" @click="showNewsSelector = true">
              选择新闻
            </t-button>
          </t-form-item>

          <NewsSelector
                  v-model="showNewsSelector"
                  :page-id="editForm.pageId"
                  :component-id="editForm.componentId"
                  @confirm="handleNewsSelect"
          />

        </template>


        <!-- ✅ Commodity 编辑改为弹窗选择器 -->
        <template v-else-if="editForm.componentType === 'commodity'">
          <t-form-item label="商品选择">
            <t-button theme="primary" @click="showCommoditySelector = true">
              选择商品
            </t-button>
          </t-form-item>

          <!-- 嵌入商品选择器 -->
          <CommoditySelector
            v-model="showCommoditySelector"
            :page-id="editForm.pageId"
            :component-id="editForm.componentId"
          />
        </template>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import ComponentService from '../api/component'
import { useRoute } from 'vue-router'
import CommoditySelector from './pageComponentManager/CommoditySelector.vue'
import NewsSelector from './pageComponentManager/NewsSelector.vue';

const route = useRoute()
const pageId = route.query.pageId || route.params.pageId || -1

// 弹框控制
const showEditDialog = ref(false)
let showCommoditySelector = ref(false)
let showNewsSelector = ref(false); // ✅ 新增新闻选择弹窗控制

const handleNewsSelect = (selectedNews) => {
  newsList.value = selectedNews
}
// 编辑表单
const editForm = reactive({
  id: null,
  pageId: '',
  componentId: '',
  componentType: '',
  dataJson: ''
})

// Swiper/News/Menus 数据
const fileList = ref([])
const swiperImages = ref([])
const newsList = ref([])
const menusData = ref([])
const uploadUrl = 'http://localhost:8083/api/upload/image'

// 表格与分页
const pageList = ref([])
const loading = ref(false)
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)

const columns = [
  { colKey: 'id', title: 'ID', width: 60 },
  { colKey: 'pageId', title: '页面ID', width: 100 },
  { colKey: 'componentId', title: '组件ID', width: 160 },
  { colKey: 'componentType', title: '组件类型', width: 120 },
  {
    colKey: 'dataJson',
    title: '组件数据',
    ellipsis: true,
    cell: (h, { row }) => h('span', JSON.stringify(row.dataJson).slice(0, 60) + '...')
  },
  { colKey: 'createdAt', title: '创建时间', width: 180 },
  { colKey: 'updatedAt', title: '更新时间', width: 180 },
  {
    colKey: 'op',
    title: '操作',
    width: 200,
    cell: (h, { row }) => [
      h('t-button', { size: 'small', theme: 'primary', onClick: () => handleEdit(row), style: 'margin-right: 8px;' }, '编辑'),
      h('t-button', { size: 'small', theme: 'danger', onClick: () => handleDelete(row.id) }, '删除')
    ]
  }
]

// ===== 上传 =====
const handleUploadSuccess = ({ response }) => {
  const data = response[0]
  if (data?.code === 0 && data.data) {
    swiperImages.value.push(data.data)
  } else {
    MessagePlugin.error('图片上传失败')
  }
}
const handleUploadRemove = ({ file }) => {
  swiperImages.value = swiperImages.value.filter(url => !url.includes(file.name))
}

// ===== 编辑逻辑 =====
const handleEdit = (row) => {
  Object.assign(editForm, row)
  showEditDialog.value = true

  if (row.componentType === 'swiper') {
    swiperImages.value = JSON.parse(row.dataJson || '{}').data || []
    fileList.value = swiperImages.value.map(url => ({
      name: url.split('/').pop(),
      url,
      status: 'success'
    }))
  } else if (row.componentType === 'news') {
    newsList.value = JSON.parse(row.dataJson || '{}').data || []
  } else if (row.componentType === 'menus') {
    menusData.value = JSON.parse(row.dataJson || '{}').data || []
  }
}

// ===== 保存 =====
const handleSaveEdit = async () => {
  try {
    const payload = { ...editForm }
    if (editForm.componentType === 'swiper') {
      payload.dataJson = JSON.stringify({ key: 'imageList', data: swiperImages.value })
    } else if (editForm.componentType === 'news') {
      payload.dataJson = JSON.stringify({ key: 'newsList', data: newsList.value })
    } else if (editForm.componentType === 'menus') {
      payload.dataJson = JSON.stringify({ key: 'menusList', data: menusData.value })
    } else if (editForm.componentType === 'commodity') {
      // 商品数据由 CommoditySelector 弹窗管理
      payload.dataJson = JSON.stringify({ key: 'commodityList', data: [] })
    } else {
      JSON.parse(editForm.dataJson) // 验证 JSON
    }

    await ComponentService.saveComponent(payload)
    MessagePlugin.success('保存成功')
    showEditDialog.value = false
    fetchList()
  } catch (e) {
    console.error(e)
    MessagePlugin.error('保存失败')
  }
}

// ===== 删除 =====
const handleDelete = (id) => {
  DialogPlugin.confirm({
    header: '确认删除？',
    body: '删除后将无法恢复，请确认是否删除该组件。',
    onConfirm: async () => {
      await ComponentService.deleteComponent(id)
      MessagePlugin.success('删除成功')
      fetchList()
    }
  })
}

// ===== 新闻逻辑 =====
const addNews = () => newsList.value.push({ title: '', image: '', desc: '' })
const removeNews = (i) => newsList.value.splice(i, 1)

// ===== Menus逻辑 =====
const addMenuItem = () => menusData.value.push({ value: '', label: '', icon: '', menu: { tabs: [] } })
const removeMenuItem = (i) => menusData.value.splice(i, 1)
const addTab = (menu) => (menu.tabs ??= []).push({ label: '', value: '' })
const removeTab = (menu, idx) => menu.tabs.splice(idx, 1)

// ===== 列表加载 =====
const fetchList = async () => {
  loading.value = true
  try {
    const res = await ComponentService.getAllPageComponentData(pageId)
    const data = res.data.data || res.data
    pageList.value = data.records || data
    total.value = data.total || pageList.value.length
  } catch {
    MessagePlugin.error('获取组件数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(fetchList)

const onPageChange = (page) => {
  pageNum.value = page.current
  fetchList()
}
const onPageSizeChange = (size) => {
  pageSize.value = size
  fetchList()
}
</script>

<style scoped>
.page-list {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 64px);
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
.menu-editor-box {
  margin-bottom: 10px;
  border: 1px solid #f0f0f0;
  padding: 10px;
  border-radius: 3px;
  width: 100%;
  box-sizing: border-box;
}
.menu-editor-box .t-form-item:last-of-type {
  margin-bottom: 8px;
}
</style>
